const fs = require('fs');
const path = require('path');
// image页面的控制器
module.exports = {
    index: (req,res) => {
        // res.end('the page: image controller');
        // 渲染模板
        // res.render('image')
        const viewModel = {
            image: {
              uniqueId: 1,
              title: '示例图片1',
              description: '这是张测试图片',
              filename: 'sample1.jpg',
              views: 0,
              likes: 0,
              timestamp: Date.now(),
            },
            comments: [
              {
                image_id: 1,
                email: 'test@testing.com',
                name: 'Test Tester',
                comment: 'Test 1',
                timestamp: Date.now(),
              },
              {
                image_id: 1,
                email: 'test@testing.com',
                name: 'Test Tester',
                comment: 'Test 2',
                timestamp: Date.now(),
              },
            ],
          };
          res.render('image', viewModel);
    },
    create: (req,res) => {
        // res.send('the image: create post controller');
        // 在上传文件的控制器中写好如何处理文件=>获取并保存图片的代码
        // 文件的本来路径
        var tempPath = req.file.path;
        // 文件名字
        var imgUrl = req.file.filename;
        // 我呢见扩展名
        var ext = path.extname(req.file.originalname).toLowerCase();
        // 新的文件路径
        var targetPath = path.resolve('./public/upload/'+imgUrl+ext);
        if(ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif'){
          fs.rename(tempPath,targetPath,(err) => {
            if(err) throw err;
            res.redirect('/images/'+imgUrl);
          })
        }else{
          fs.unlink(tempPath,(err) => {
            if(err) throw err;
            res.json(500,{error: '只允许上传图片文件'})
          })
        }
    },
    like: (req,res) => {
        res.send('the image: like post controller');
    },
    comment: (req,res) => {
        res.send('the image: comment post controller');
    }
}